<template>
  <div class="app-container">
    <!--查询表单-->
    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="6">
            <el-form-item label="用户名">
              <el-input
                style="width: 100%"
                v-model="searchObj.keyword"
                placeholder="用户名/昵称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin-left: 10px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="fetchData()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetData()"
              >重置</el-button
            >
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-button
              type="success"
              icon="el-icon-plus"
              size="mini"
              @click="handleSave()"
              :disabled="$hasBP('btn.sysUser.add') === false"
              >添加</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-minus"
              size="mini"
              :disabled="isDisabled && $hasBP('btn.sysUser.remove') === false"
              @click="deleteBatch()"
              >批量删除</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 分配角色表单 -->
    <div class="toAssignForm">
      <el-dialog
        :title="sysUser.username + ':分配角色'"
        :visible.sync="toAssigndialogFormVisible"
      >
        <el-form>
          <el-form-item label="已拥有角色">
            <el-tag
              type="info"
              v-for="(item, index) in hadRoles"
              :key="index"
              style="margin-left: 10px"
              >{{ item.roleName }}</el-tag
            >
          </el-form-item>
        </el-form>
        <hr />
        <el-form>
          <el-form-item label="所有角色|如需重新设置请重复勾选,否则会覆盖">
            <el-table
              :data="allRoles"
              tooltip-effect="dark"
              style="width: 100%"
              @selection-change="selectRoleList"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column label="角色" prop="roleName" />
            </el-table>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="toAssigndialogFormVisible = false"
            >取 消</el-button
          >
          <el-button type="primary" @click="doAssign(sysUser.id, doAssignList)"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
    <!-- 添加/修改表单 -->
    <div class="saveForm">
      <el-dialog
        :title="sysUser.id ? '修改' : '添加'"
        :visible.sync="dialogFormVisible"
      >
        <el-form :model="sysUser">
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input v-model="sysUser.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" :label-width="formLabelWidth">
            <el-input v-model="sysUser.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" :label-width="formLabelWidth">
            <el-input v-model="sysUser.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="状态" :label-width="formLabelWidth">
            <el-select v-model="sysUser.status" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="头像">
            <el-row>
              <el-col :span="8">
                <el-upload
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :multiple="true"
                  ref="upload"
                  action="http://localhost:8080/api/system/fileUpload"
                  class="upload-demo"
                  list-type="picture-card"
                >
                  <i class="el-icon-plus" />
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png/gif文件，且不超过2MB
                  </div>
                </el-upload>
              </el-col>
              <el-col :span="6">
                <el-image
                  v-if="imgUrl"
                  :src="imgUrl"
                  style="width: 150px; height: 150px"
                ></el-image>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false;imgUrl='';">取 消</el-button>
          <el-button type="primary" @click="sysUser.id ? update() : save()"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
    <el-table
      v-loading="listLoading"
      :data="userList"
      :key="itemKey"
      stripe
      border
      style="width: 100%; margin-top: 10px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="180" />
      <el-table-column prop="name" label="昵称" width="180" />
      <el-table-column prop="phone" label="手机号" width="180" />
      <el-table-column prop="status" label="状态" width="70">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status === 1">正常</el-tag>
          <el-tag type="danger" v-if="scope.row.status === 0">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="头像" width="100">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.headUrl"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="添加时间" width="180" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="handleEdit(scope.row)"
            title="修改"
            :disabled="$hasBP('btn.sysUser.update') === false"
          />
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeDataById(scope.row.id)"
            title="删除"
            
          />
          <el-button
            type="primary"
            icon="el-icon-warning"
            size="mini"
            @click="toAssign(scope.row)"
            :disabled="$hasBP('btn.sysUser.assignRole') === false"
            title="分配角色"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="text-align: center"
    >
    </el-pagination>
  </div>
</template>
<script>
import * as api from "@/api/system/user/user";

export default {
  data() {
    return {
      userList: [],
      total: 0,
      limit: 5,
      currentPage: 1,
      searchObj: {},
      labelWidth: 100,
      listLoading: true,
      formLabelWidth: "100",
      itemKey: Math.random(),
      sysUser: {},
      dialogFormVisible: false,
      toAssigndialogFormVisible: false,
      userIDS: [],
      isDisabled: true,
      imgUrl: '',
      options: [
        { value: 1, label: "正常" },
        { value: 0, label: "停用" },
      ],
      hadRoles: [],
      allRoles: [],
      doAssignList: [],
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    buttonIsDisabled() {
      if (this.userIDS.length == 0) {
        this.isDisabled = true;
      }
      if (this.userIDS.length > 0) {
        this.isDisabled = false;
      }
    },
    fetchData() {
      api
        .getPageList(this.currentPage, this.limit, this.searchObj)
        .then((response) => {
          this.userList = response.data.records;
          this.total = response.data.total;
          this.listLoading = false;
        });
    },
    resetData() {
      this.searchObj = {};
      this.fetchData();
    },
    handleSizeChange(val) {
      this.limit = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    handleSelectionChange(val) {
      //每次监听都重新向空数组中加值,不然会造成取消的值无法从数组中取出
      this.userIDS = [];
      for (var i = 0; i < val.length; i++) {
        this.userIDS.push(val[i].id);
      }
      this.buttonIsDisabled();
      // console.log(this.userIDS)
    },
    removeDataById(id) {
      this.$confirm("此操作将永久删除, 是否继续?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        api.removeByID(id).then((response) => {
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.fetchData();
        });
      });
    },
    handleSave() {
      this.sysUser = {};
      this.dialogFormVisible = true;
      //默认密码
      this.sysUser.password = "admin123";
      this.imgUrl = "";
    },
    handleEdit(user) {
      console.log(user)
      this.sysUser = user
      //如果头像url为空且修改时不准备上传,保持原头像,使用imgUrl暂时接收图片地址
      if (this.imgUrl == '') {
        this.imgUrl = user.headUrl
      }
      this.dialogFormVisible = true
    },
    save() {
      this.sysUser.headUrl = this.imgUrl;
      api
        .saveUser(this.sysUser)
        .then((response) => {
          this.$message({
            type: "success",
            message: "添加成功",
          });
          this.sysUser = {};
          this.imgUrl = "";
          this.fetchData();
          this.openNotice();
        })
        .catch((response) => {
          this.$message.error(response.error)
          this.sysUser = {}
          this.imgUrl = ""
          this.fetchData()
        });
      this.dialogFormVisible = false;
    },
    update() {
      this.sysUser.headUrl = this.imgUrl;
      api
        .updateUser(this.sysUser)
        .then((response) => {
          this.$message({
            type: "success",
            message: "修改成功",
          });
          this.sysUser = {};
          this.imgUrl = "";
          this.fetchData();
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: "修改失败",
          });
          this.sysUser = {};
          this.imgUrl = "";
          this.fetchData();
        });
      this.dialogFormVisible = false;
    },
    deleteBatch() {
      this.$confirm("此操作将永久删除数据, 是否继续?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        api
          .deleteBatch(this.userIDS)
          .then((response) => {
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.fetchData();
          })
          .catch((response) => {
            this.$message({
              type: "error",
              message: "删除失败",
            });
            this.fetchData();
          });
      });
    },
    //图片上传成功回调
    handleAvatarSuccess(res, file) {
      //上传图片后imgUrl接收返回的图片地址
      this.imgUrl = file.response.data;
      this.$refs.upload.clearFiles();
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt5M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      return isJPG && isLt5M;
    },
    //获取角色列表,弹窗
    toAssign(user) {
      this.sysUser = user;
      this.toAssigndialogFormVisible = true;
      this.hadRoles = [];
      this.allRoles = [];
      api
        .toAssign(user.id)
        .then((response) => {
          console.log(response.data);
          if (response.data.hadRoles != null && response.data.hadRoles != []) {
            this.hadRoles = response.data.hadRoles;
            this.allRoles = response.data.allRoles;
          } else {
            this.hadRoles = [];
          }
          this.allRoles = response.data.allRoles;
        })
        .catch((response) => {
          this.$message().error(response);
        });
    },
    //选择角色列表后回调
    selectRoleList(val) {
      // console.log(val)
      this.doAssignList = [];
      for (var i = 0; i < val.length; i++) {
        this.doAssignList.push(val[i].id);
      }
      console.log(this.doAssignList);
    },
    //分配角色
    doAssign(id, roleIDs) {
      api
        .doAssign(id, roleIDs)
        .then((response) => {
          this.$message.success("设置成功");
          this.toAssigndialogFormVisible = false;
        })
        .catch((response) => {
          this.$message.error(response.error);
          this.toAssigndialogFormVisible = false;
        });
    },
    openNotice() {
      const h = this.$createElement;

      this.$notify.info({
        title: "注意:",
        message: h(
          "i",
          { style: "color: teal" },
          "添加的默认密码为admin123,请用户个人登录后修改"
        ),
      });
    },
  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>